package com.ruoyi.auth.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.TokenConstants;
import com.ruoyi.system.api.RemoteLogService;
import com.ruoyi.system.api.domain.SysOperLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.auth.form.LoginBody;
import com.ruoyi.auth.form.RegisterBody;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;

/**
 * token 控制
 * 
 * @author ruoyi
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private RemoteLogService remoteLogService;

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody)
    {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }

    /**
     * nginx 验证权限才能访问
     * @param request
     * @param response
     * @return
     */
    @GetMapping("userCheck")
    public ResponseEntity<Boolean> authImages(HttpServletRequest request, HttpServletResponse response) {
        boolean isValid = false;
        SysOperLog sysOperLog = new SysOperLog();
        //获取请求头部
        try {
            String authorizationParam = request.getHeader(TokenConstants.AUTHENTICATION);
            sysOperLog.setTitle("nginx验证权限才能访问");
            sysOperLog.setOperParam(authorizationParam);
            remoteLogService.saveLog(sysOperLog, SecurityConstants.AUTHORIZATION_HEADER);
            String token = authorizationParam.split("=")[1];
            if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX)) {
                token = token.replace(TokenConstants.PREFIX, "");
            }
            if (StringUtils.isNoneBlank(token)) { //验证token有效性
//                Object cacheObject = redisService.getCacheObject(CacheConstants.LOGIN_TOKEN_KEY + token);
//                if(ObjectUtils.isNotEmpty(cacheObject)) {
//                    isValid = true;
//                }
            }
            sysOperLog.setOperParam(String.valueOf(isValid));
            remoteLogService.saveLog(sysOperLog, SecurityConstants.AUTHORIZATION_HEADER);
            if (!isValid) {
                response.setHeader("WWW-authenticate", "Basic realm=\"没有权限\"");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(false);
            }
            return ResponseEntity.ok(true);
        } catch (Exception e) {
            sysOperLog.setOperParam(e.getMessage());
            remoteLogService.saveLog(sysOperLog, SecurityConstants.AUTHORIZATION_HEADER);
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(false);
        }
    }
}
